# -*- coding: utf-8 -*-
"""
IP地址管理模块
"""

from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QTableWidget, 
                            QTableWidgetItem, QPushButton, QLineEdit, QLabel, 
                            QComboBox, QMessageBox, QDialog, QFormLayout, QDialogButtonBox, QTabWidget,
                            QListWidget, QListWidgetItem, QSplitter, QFrame, QGroupBox, QInputDialog, QStyle)
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QColor, QFont
from models import IPManagementModel
from database import Database

class IPManagementWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.model = IPManagementModel()
        self.db = Database()
        self.init_ui()
        self.load_network_segments()
    
    def init_ui(self):
        """初始化用户界面"""
        layout = QVBoxLayout(self)
        layout.setContentsMargins(10, 10, 10, 10)
        layout.setSpacing(10)
        
        # 创建分割器
        splitter = QSplitter(Qt.Horizontal)
        splitter.setHandleWidth(2)
        layout.addWidget(splitter)
        
        # 左侧网段管理面板
        left_panel = QFrame()
        left_panel.setFrameStyle(QFrame.NoFrame)
        left_layout = QVBoxLayout(left_panel)
        left_layout.setContentsMargins(0, 0, 5, 0)
        left_layout.setSpacing(10)
        
        # 网段管理组
        network_group = QGroupBox("🌐 网段管理")
        network_layout = QVBoxLayout(network_group)
        network_layout.setSpacing(5)
        
        # 网段列表
        self.network_list = QListWidget()
        self.network_list.itemClicked.connect(self.on_network_selected)
        network_layout.addWidget(self.network_list)
        
        # 网段操作按钮
        network_btn_layout = QHBoxLayout()
        
        self.add_network_btn = QPushButton("➕ 添加网段")
        self.add_network_btn.clicked.connect(self.add_network_segment)
        
        self.delete_network_btn = QPushButton("🗑️ 删除网段")
        self.delete_network_btn.clicked.connect(self.delete_network_segment)
        
        self.refresh_network_btn = QPushButton("🔄 刷新")
        self.refresh_network_btn.clicked.connect(self.load_network_segments)
        
        network_btn_layout.addWidget(self.add_network_btn)
        network_btn_layout.addWidget(self.delete_network_btn)
        network_btn_layout.addWidget(self.refresh_network_btn)
        network_layout.addLayout(network_btn_layout)
        
        left_layout.addWidget(network_group)
        splitter.addWidget(left_panel)
        
        # 右侧IP管理面板
        right_panel = QFrame()
        right_panel.setFrameStyle(QFrame.NoFrame)
        right_layout = QVBoxLayout(right_panel)
        right_layout.setContentsMargins(5, 0, 0, 0)
        right_layout.setSpacing(10)
        
        # 搜索栏
        search_layout = QHBoxLayout()
        
        search_label = QLabel("🔍 搜索:")
        self.search_input = QLineEdit()
        self.search_input.setPlaceholderText("输入IP地址、设备类型、部门、用途或备注...")
        self.search_input.textChanged.connect(self.search_data)
        
        search_layout.addWidget(search_label)
        search_layout.addWidget(self.search_input)
        search_layout.addStretch()
        
        # 操作按钮
        self.add_button = QPushButton("➕ 添加IP")
        self.add_button.clicked.connect(self.add_ip)
        
        self.edit_button = QPushButton("✏️ 编辑IP")
        self.edit_button.clicked.connect(self.edit_ip)
        
        self.delete_button = QPushButton("🗑️ 删除IP")
        self.delete_button.clicked.connect(self.delete_ip)
        
        self.refresh_button = QPushButton("🔄 刷新")
        self.refresh_button.clicked.connect(self.load_network_segments)
        
        search_layout.addWidget(self.add_button)
        search_layout.addWidget(self.edit_button)
        search_layout.addWidget(self.delete_button)
        search_layout.addWidget(self.refresh_button)
        
        right_layout.addLayout(search_layout)
        
        # 状态标签页
        self.tab_widget = QTabWidget()
        right_layout.addWidget(self.tab_widget)
        
        splitter.addWidget(right_panel)
        
        # 设置分割器比例
        splitter.setSizes([200, 1000])
    
    def load_network_segments(self):
        """加载网段并创建标签页"""
        # 清空现有标签页
        self.tab_widget.clear()
        
        try:
            # 获取字典表和IP管理表中的所有网段
            conn = self.db.get_connection()
            cursor = conn.cursor()
            
            # 从字典表获取网段
            cursor.execute('SELECT dict_value FROM dictionary WHERE dict_name = "网段" ORDER BY dict_value')
            dict_segments = [row[0] for row in cursor.fetchall()]
            
            # 从IP管理表获取网段
            cursor.execute('SELECT DISTINCT network_segment FROM ip_management WHERE network_segment IS NOT NULL ORDER BY network_segment')
            ip_segments = [row[0] for row in cursor.fetchall()]
            
            # 合并网段列表，去重
            all_segments = list(set(dict_segments + ip_segments))
            all_segments.sort()
            
            conn.close()
            
            # 更新网段列表
            self.network_list.clear()
            # 添加"全部网段"选项
            all_item = QListWidgetItem("全部网段")
            all_item.setIcon(self.style().standardIcon(QStyle.SP_DirHomeIcon))
            self.network_list.addItem(all_item)
            
            for segment in all_segments:
                item = QListWidgetItem(segment)
                self.network_list.addItem(item)
            
            # 添加状态标签页
            status_table = self.create_table()
            self.tab_widget.addTab(status_table, "全部")
            self.load_all_data(status_table)
            
            enabled_table = self.create_table()
            self.tab_widget.addTab(enabled_table, "启用")
            self.load_data_by_status("启用", enabled_table)
            
            disabled_table = self.create_table()
            self.tab_widget.addTab(disabled_table, "禁用")
            self.load_data_by_status("禁用", disabled_table)
            
            # 添加网段标签页（排除"服务器网段"）
            for segment in all_segments:
                if segment != "服务器网段":  # 排除"服务器网段"
                    table = self.create_table()
                    self.tab_widget.addTab(table, segment)
                    self.load_data_for_segment(segment, table)
            
        except Exception as e:
            QMessageBox.critical(self, "错误", f"加载网段失败：{str(e)}")
    
    def on_network_selected(self, item):
        """网段选择事件 - 实现联动操作"""
        segment_name = item.text()
        
        if segment_name == "全部网段":
            # 恢复全局视图
            self.load_network_segments()
            self.search_input.setPlaceholderText("输入IP地址、设备类型、部门、用途或备注...")
        else:
            # 1. 数据过滤：清空现有标签页并重新创建，只显示选中网段的数据
            self.tab_widget.clear()
            
            # 2. 默认视图：创建"全部"标签页并显示该网段的所有IP数据
            all_table = self.create_table()
            self.tab_widget.addTab(all_table, "全部")
            self.load_data_for_segment(segment_name, all_table)
            
            # 3. 创建状态标签页（启用/禁用）但仅显示该网段的数据
            enabled_table = self.create_table()
            self.tab_widget.addTab(enabled_table, "启用")
            self.load_data_for_segment_by_status(segment_name, "启用", enabled_table)
            
            disabled_table = self.create_table()
            self.tab_widget.addTab(disabled_table, "禁用")
            self.load_data_for_segment_by_status(segment_name, "禁用", disabled_table)
            
            # 4. 界面聚焦：默认选中"全部"标签页
            self.tab_widget.setCurrentIndex(0)
            
            # 5. 更新搜索提示文本
            self.search_input.setPlaceholderText(f"在'{segment_name}'网段中搜索IP地址、设备类型、部门、用途或备注...")
    
    def add_network_segment(self):
        """添加网段"""
        segment_name, ok = QInputDialog.getText(self, "添加网段", "请输入网段名称:")
        if ok and segment_name:
            # 检查网段是否已存在
            for i in range(self.network_list.count()):
                if self.network_list.item(i).text() == segment_name:
                    QMessageBox.warning(self, "警告", "网段已存在")
                    return
            
            # 添加到数据库字典表
            try:
                self.db.add_dictionary_value("网段", segment_name, "自定义网段")
                # 刷新网段列表
                self.load_network_segments()
                QMessageBox.information(self, "成功", "网段添加成功")
            except Exception as e:
                QMessageBox.critical(self, "错误", f"添加网段失败：{str(e)}")
    
    def delete_network_segment(self):
        """删除网段"""
        current_item = self.network_list.currentItem()
        if not current_item:
            QMessageBox.warning(self, "警告", "请选择要删除的网段")
            return
        
        segment_name = current_item.text()
        
        # 检查该网段下是否有IP
        try:
            conn = self.db.get_connection()
            cursor = conn.cursor()
            cursor.execute('SELECT COUNT(*) FROM ip_management WHERE network_segment = ?', (segment_name,))
            count = cursor.fetchone()[0]
            conn.close()
            
            if count > 0:
                reply = QMessageBox.question(self, "确认", f"网段 '{segment_name}' 下还有 {count} 个IP地址，确定要删除吗？",
                                           QMessageBox.Yes | QMessageBox.No)
                if reply == QMessageBox.No:
                    return
            
            # 从字典表中删除网段
            try:
                conn = self.db.get_connection()
                cursor = conn.cursor()
                cursor.execute('DELETE FROM dictionary WHERE dict_name = ? AND dict_value = ?', ("网段", segment_name))
                conn.commit()
                conn.close()
                
                # 刷新网段列表
                self.load_network_segments()
                QMessageBox.information(self, "成功", "网段删除成功")
            except Exception as e:
                QMessageBox.critical(self, "错误", f"删除网段失败：{str(e)}")
                
        except Exception as e:
            QMessageBox.critical(self, "错误", f"检查网段数据失败：{str(e)}")
    
    def create_table(self):
        """创建表格"""
        table = QTableWidget()
        table.setColumnCount(9)  # 增加了状态和备注列
        table.setHorizontalHeaderLabels([
            "🌐 IP地址", "🖥️ 设备类型", "🏢 部门", "📋 用途描述", 
            "📦 关联资产编号", "👤 负责人", "🌍 网段", "✅ 状态", "📝 备注"
        ])
        table.setSelectionBehavior(QTableWidget.SelectRows)
        table.setSelectionMode(QTableWidget.SingleSelection)
        table.setAlternatingRowColors(True)
        
        # 设置列宽
        table.setColumnWidth(0, 130)
        table.setColumnWidth(1, 110)
        table.setColumnWidth(2, 120)
        table.setColumnWidth(3, 160)
        table.setColumnWidth(4, 130)
        table.setColumnWidth(5, 100)
        table.setColumnWidth(6, 100)
        table.setColumnWidth(7, 80)  # 状态列
        table.setColumnWidth(8, 150)  # 备注列
        
        # 设置表头字体
        header = table.horizontalHeader()
        header.setFont(QFont("Microsoft YaHei", 10, QFont.Bold))
        
        return table
    
    def load_data_for_segment(self, segment, table):
        """加载指定网段的数据"""
        try:
            data = self.model.get_ips_by_segment(segment)
            self.populate_table(table, data)
        except Exception as e:
            QMessageBox.critical(self, "错误", f"加载网段数据失败：{str(e)}")
    
    def load_data_by_status(self, status, table):
        """根据状态加载数据"""
        try:
            data = self.model.get_ips_by_status(status)
            self.populate_table(table, data)
        except Exception as e:
            QMessageBox.critical(self, "错误", f"加载{status}状态数据失败：{str(e)}")
    
    def load_data_for_segment_by_status(self, segment, status, table):
        """根据网段和状态加载数据"""
        try:
            data = self.model.get_ips_by_segment_and_status(segment, status)
            self.populate_table(table, data)
        except Exception as e:
            QMessageBox.critical(self, "错误", f"加载网段{segment}的{status}状态数据失败：{str(e)}")
    
    def load_all_data(self, table):
        """加载所有数据"""
        try:
            data = self.model.get_all_ips()
            self.populate_table(table, data)
        except Exception as e:
            QMessageBox.critical(self, "错误", f"加载数据失败：{str(e)}")
    
    def populate_table(self, table, data):
        """填充表格数据"""
        table.setRowCount(len(data))
        
        for row, item in enumerate(data):
            # IP地址
            ip_item = QTableWidgetItem(item['ip_address'])
            ip_item.setData(Qt.UserRole, item['id'])
            table.setItem(row, 0, ip_item)
            
            # 设备类型
            table.setItem(row, 1, QTableWidgetItem(item['device_type']))
            
            # 部门
            table.setItem(row, 2, QTableWidgetItem(item['department']))
            
            # 用途描述
            table.setItem(row, 3, QTableWidgetItem(item['purpose']))
            
            # 关联资产编号
            table.setItem(row, 4, QTableWidgetItem(item['asset_id'] or ""))
            
            # 负责人
            table.setItem(row, 5, QTableWidgetItem(item['responsible_person'] or ""))
            
            # 网段
            table.setItem(row, 6, QTableWidgetItem(item['network_segment'] or ""))
            
            # 状态
            status_item = QTableWidgetItem(item['status'] or "")
            if item['status'] == '禁用':
                # 设置禁用状态的视觉效果
                font = status_item.font()
                font.setItalic(True)
                status_item.setFont(font)
                status_item.setForeground(QColor(160, 160, 160))  # 灰色字体
            table.setItem(row, 7, status_item)
            
            # 备注
            table.setItem(row, 8, QTableWidgetItem(item['remark'] or ""))
    
    def search_data(self):
        """搜索数据"""
        keyword = self.search_input.text().strip()
        if keyword:
            try:
                # 在当前激活的标签页中搜索
                current_table = self.tab_widget.currentWidget()
                if current_table:
                    # 获取当前选中的网段（如果有）
                    current_network_item = self.network_list.currentItem()
                    if current_network_item:
                        # 在特定网段中搜索
                        segment = current_network_item.text()
                        data = self.model.search_ips_in_segment(segment, keyword)
                    else:
                        # 全局搜索
                        data = self.model.search_ips(keyword)
                    self.populate_table(current_table, data)
            except Exception as e:
                QMessageBox.critical(self, "错误", f"搜索失败：{str(e)}")
        else:
            # 恢复当前标签页数据
            current_index = self.tab_widget.currentIndex()
            if current_index != -1:
                current_tab_text = self.tab_widget.tabText(current_index)
                current_table = self.tab_widget.currentWidget()
                
                # 获取当前选中的网段（如果有）
                current_network_item = self.network_list.currentItem()
                if current_network_item:
                    segment = current_network_item.text()
                    if current_tab_text == "全部":
                        self.load_data_for_segment(segment, current_table)
                    elif current_tab_text == "启用":
                        self.load_data_for_segment_by_status(segment, "启用", current_table)
                    elif current_tab_text == "禁用":
                        self.load_data_for_segment_by_status(segment, "禁用", current_table)
                else:
                    # 全局视图
                    if current_tab_text == "全部":
                        self.load_all_data(current_table)
                    elif current_tab_text == "启用":
                        self.load_data_by_status("启用", current_table)
                    elif current_tab_text == "禁用":
                        self.load_data_by_status("禁用", current_table)
                    else:
                        self.load_data_for_segment(current_tab_text, current_table)
    
    def add_ip(self):
        """添加IP"""
        dialog = IPDialog(self, self.db)
        if dialog.exec_() == QDialog.Accepted:
            # 保持当前网段选择状态
            current_item = self.network_list.currentItem()
            if current_item and current_item.text() != "全部网段":
                # 如果选择了特定网段，刷新该网段视图
                self.on_network_selected(current_item)
            else:
                # 否则刷新全局视图
                self.load_network_segments()
    
    def edit_ip(self):
        """编辑IP"""
        current_table = self.tab_widget.currentWidget()
        if current_table is None:
            QMessageBox.warning(self, "警告", "当前没有可编辑的数据")
            return
            
        current_row = current_table.currentRow()
        if current_row == -1:
            QMessageBox.warning(self, "警告", "请选择要编辑的记录")
            return
        
        item = current_table.item(current_row, 0)
        ip_id = item.data(Qt.UserRole)
        
        dialog = IPDialog(self, self.db, ip_id)
        if dialog.exec_() == QDialog.Accepted:
            # 保持当前网段选择状态
            current_item = self.network_list.currentItem()
            if current_item and current_item.text() != "全部网段":
                # 如果选择了特定网段，刷新该网段视图
                self.on_network_selected(current_item)
            else:
                # 否则重新加载当前标签页的数据
                current_index = self.tab_widget.currentIndex()
                current_tab_text = self.tab_widget.tabText(current_index)
                if current_tab_text == "全部":
                    self.load_all_data(current_table)
                elif current_tab_text == "启用":
                    self.load_data_by_status("启用", current_table)
                elif current_tab_text == "禁用":
                    self.load_data_by_status("禁用", current_table)
                else:
                    self.load_data_for_segment(current_tab_text, current_table)
    
    def delete_ip(self):
        """删除IP"""
        current_table = self.tab_widget.currentWidget()
        if current_table is None:
            QMessageBox.warning(self, "警告", "当前没有可删除的数据")
            return
            
        current_row = current_table.currentRow()
        if current_row == -1:
            QMessageBox.warning(self, "警告", "请选择要删除的记录")
            return
        
        reply = QMessageBox.question(self, "确认", "确定要删除选中的IP记录吗？",
                                   QMessageBox.Yes | QMessageBox.No)
        
        if reply == QMessageBox.Yes:
            item = current_table.item(current_row, 0)
            ip_id = item.data(Qt.UserRole)
            
            try:
                self.model.delete_ip(ip_id)
                # 保持当前网段选择状态
                current_item = self.network_list.currentItem()
                if current_item and current_item.text() != "全部网段":
                    # 如果选择了特定网段，刷新该网段视图
                    self.on_network_selected(current_item)
                else:
                    # 否则重新加载所有标签页
                    self.load_network_segments()
                QMessageBox.information(self, "成功", "IP记录删除成功")
            except Exception as e:
                QMessageBox.critical(self, "错误", f"删除失败：{str(e)}")

class IPDialog(QDialog):
    def __init__(self, parent, db, ip_id=None):
        super().__init__(parent)
        self.db = db
        self.ip_id = ip_id
        self.model = IPManagementModel()
        
        self.setWindowTitle("➕ 添加IP" if ip_id is None else "✏️ 编辑IP")
        self.setModal(True)
        self.resize(500, 450)
        
        # 设置对话框样式
        self.setStyleSheet("""
            QDialog {
                background-color: #f8f9fa;
                font-family: "Microsoft YaHei";
            }
            QLabel {
                color: #495057;
                font-weight: 600;
                font-size: 14px;
            }
            QPushButton {
                background-color: #4a90e2;
                color: white;
                border: none;
                border-radius: 4px;
                padding: 6px 12px;
                font-size: 13px;
                font-weight: 500;
            }
            QPushButton:hover {
                background-color: #357abd;
            }
            QPushButton:pressed {
                background-color: #2968aa;
            }
        """)
        
        self.init_ui()
        
        if ip_id:
            self.load_ip_data()
        else:
            # 默认状态为启用
            self.status_combo.setCurrentText("启用")
    
    def init_ui(self):
        """初始化界面"""
        layout = QVBoxLayout(self)
        layout.setSpacing(15)
        layout.setContentsMargins(20, 20, 20, 20)
        
        # 标题
        title_label = QLabel("🌐 IP地址信息")
        title_label.setStyleSheet("font-size: 16px; font-weight: bold; color: #4a90e2; margin-bottom: 10px;")
        layout.addWidget(title_label)
        
        # 表单布局
        form_layout = QFormLayout()
        
        # IP地址
        self.ip_input = QLineEdit()
        self.ip_input.setPlaceholderText("例如: 192.168.1.100")
        form_layout.addRow("🌐 IP地址*:", self.ip_input)
        
        # 设备类型
        self.device_type_combo = QComboBox()
        device_types = self.db.get_dictionary_values("设备类型")
        self.device_type_combo.addItems(device_types)
        self.device_type_combo.setEditable(True)
        form_layout.addRow("🖥️ 设备类型*:", self.device_type_combo)
        
        # 部门
        self.department_input = QLineEdit()
        self.department_input.setPlaceholderText("例如: 信息科")
        form_layout.addRow("🏢 部门*:", self.department_input)
        
        # 用途描述
        self.purpose_input = QLineEdit()
        self.purpose_input.setPlaceholderText("例如: Web服务器")
        form_layout.addRow("📋 用途描述*:", self.purpose_input)
        
        # 关联资产编号
        self.asset_id_input = QLineEdit()
        self.asset_id_input.setPlaceholderText("例如: PC-001")
        form_layout.addRow("📦 关联资产编号:", self.asset_id_input)
        
        # 负责人
        self.responsible_person_input = QLineEdit()
        self.responsible_person_input.setPlaceholderText("例如: 张三")
        form_layout.addRow("👤 负责人:", self.responsible_person_input)
        
        # 网段
        self.network_segment_combo = QComboBox()
        network_segments = self.db.get_dictionary_values("网段")
        self.network_segment_combo.addItems(network_segments)
        self.network_segment_combo.setEditable(True)
        form_layout.addRow("🌍 网段:", self.network_segment_combo)
        
        # 状态
        self.status_combo = QComboBox()
        self.status_combo.addItems(["✅ 启用", "❌ 禁用"])
        form_layout.addRow("🔄 状态:", self.status_combo)
        
        # 备注
        self.remark_input = QLineEdit()
        self.remark_input.setPlaceholderText("可选的备注信息")
        form_layout.addRow("📝 备注:", self.remark_input)
        
        layout.addLayout(form_layout)
        
        # 按钮区域
        button_layout = QHBoxLayout()
        
        # 自定义按钮
        ok_button = QPushButton("✅ 确认")
        ok_button.clicked.connect(self.accept)
        ok_button.setStyleSheet("background-color: #28a745;")
        
        cancel_button = QPushButton("❌ 取消")
        cancel_button.clicked.connect(self.reject)
        cancel_button.setStyleSheet("background-color: #6c757d;")
        
        button_layout.addStretch()
        button_layout.addWidget(ok_button)
        button_layout.addWidget(cancel_button)
        
        layout.addLayout(button_layout)
    
    def load_ip_data(self):
        """加载IP数据"""
        try:
            conn = self.db.get_connection()
            cursor = conn.cursor()
            cursor.execute('SELECT * FROM ip_management WHERE id=?', (self.ip_id,))
            data = cursor.fetchone()
            conn.close()
            
            if data:
                self.ip_input.setText(data['ip_address'])
                self.device_type_combo.setCurrentText(data['device_type'])
                self.department_input.setText(data['department'])
                self.purpose_input.setText(data['purpose'])
                self.asset_id_input.setText(data['asset_id'] or "")
                self.responsible_person_input.setText(data['responsible_person'] or "")
                self.network_segment_combo.setCurrentText(data['network_segment'] or "")
                self.status_combo.setCurrentText(data['status'] or "启用")
                self.remark_input.setText(data['remark'] or "")
                
        except Exception as e:
            QMessageBox.critical(self, "错误", f"加载数据失败：{str(e)}")
    
    def accept(self):
        """确定按钮事件"""
        # 获取表单数据
        ip_address = self.ip_input.text().strip()
        device_type = self.device_type_combo.currentText().strip()
        department = self.department_input.text().strip()
        purpose = self.purpose_input.text().strip()
        asset_id = self.asset_id_input.text().strip() or None
        responsible_person = self.responsible_person_input.text().strip() or None
        network_segment = self.network_segment_combo.currentText().strip() or None
        status = self.status_combo.currentText().strip()
        remark = self.remark_input.text().strip() or None
        
        # 验证必填字段
        if not all([ip_address, device_type, department, purpose]):
            QMessageBox.warning(self, "警告", "请填写所有必填字段")
            return
        
        # 验证IP地址格式（简单验证）
        if not self.validate_ip(ip_address):
            QMessageBox.warning(self, "警告", "IP地址格式不正确")
            return
        
        try:
            if self.ip_id:
                # 更新
                self.model.update_ip(
                    self.ip_id, ip_address, device_type, department, purpose,
                    asset_id, responsible_person, network_segment, status, remark
                )
            else:
                # 添加
                self.model.add_ip(
                    ip_address, device_type, department, purpose,
                    asset_id, responsible_person, network_segment, status, remark
                )
            
            super().accept()
            
        except Exception as e:
            QMessageBox.critical(self, "错误", f"保存失败：{str(e)}")
    
    def validate_ip(self, ip):
        """简单验证IP地址格式"""
        parts = ip.split('.')
        if len(parts) != 4:
            return False
        try:
            for part in parts:
                num = int(part)
                if num < 0 or num > 255:
                    return False
            return True
        except ValueError:
            return False